﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;

namespace MVVMFramework.View
{
    /// <summary>
    /// A value converter which contains a list of IValueConverters and invokes their Convert or ConvertBack methods in the order that they exist in the list.
    /// </summary>
    [System.Windows.Markup.ContentProperty("Converters")]
    public class SequentialValueConverter :  IValueConverter
    {
        private readonly List<IValueConverter> converters = new List<IValueConverter>();
        public List<IValueConverter> Converters
        {
            get
            {
                return converters;
            }
        }

        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            object returnValue = value;

            for (int n = 0; n < converters.Count; n++)
            {
                IValueConverter converter = converters[n];
                returnValue = converter.Convert(returnValue, targetType, parameter, culture);
            }

            return returnValue;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            object returnValue = value;

            for (int n = converters.Count - 1; n >=0 ; n--)
            {
                IValueConverter converter = converters[n];
                returnValue = converter.ConvertBack(returnValue, targetType, parameter, culture);
            }

            return returnValue;
        }

        #endregion
    }
}
